package com.zqz.webserver.herocat;

import com.zqz.webserver.servlet.HeroResponse;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.util.internal.StringUtil;

import java.nio.charset.StandardCharsets;

public class HttpCustomResponse implements HeroResponse {

    private final HttpRequest httpRequest;

    private final ChannelHandlerContext handlerContext;

    public HttpCustomResponse(HttpRequest httpRequest, ChannelHandlerContext handlerContext) {
        this.httpRequest = httpRequest;
        this.handlerContext = handlerContext;
    }

    @Override
    public void write(String content) throws Exception {

        if (StringUtil.isNullOrEmpty(content)) {
            return;
        }

        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.wrappedBuffer(content.getBytes(StandardCharsets.UTF_8))
        );

        HttpHeaders headers = response.headers()
                .set(HttpHeaderNames.CONTENT_TYPE, "text/json")
                .set(HttpHeaderNames.CONTENT_LENGTH, content.getBytes().length)
                .set(HttpHeaderNames.EXPIRES, 0);
        if (HttpUtil.isKeepAlive(httpRequest)) {
            headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
        }

        handlerContext.writeAndFlush(response);
    }
}
